Chapter 4. Clustering and classification

In this chapter we will learn how to classify data using linear discriminant analysis and k-means, one of the most known methods of clustering.

3.1 Description and overview of the data

We will use the dataset called Boston from the MASS package. The data has 506 observations from 14 variables. The dataset gives different housing values in suburbs of Boston. E.g.: per capita crime rate by town, proportion of industries per town, nitrogen oxides concentration, etc. More information about the data can be found here: https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/Boston.html

library(MASS)
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston)
## [1] 506  14

Next we can see a graphical overview of the data and the summaries of the variables.

Because we have so many variables, it would be hard to do a scatter plot for each combination of variables, an easier way to see what is the relationship between variables is making a correlation matrix.

In our matrix we can see visually which variables are more related and if they are positively or negatively related (with the colours and size of the circles), and we can also see the correlations numerically.

The highest correlation we find it between rad and tax, which means index of accessibility to radial highways and full-value property-tax rate, so obviously, the tax rate depends a lot on whether the property is easily accessible by radial highways or not. We can see how many other variables are also well correlated in the graphic.

install.packages(“corrplot”) install.packages(“tidyverse”)

library(corrplot)
## corrplot 0.84 loaded
library(tidyverse)
## -- Attaching packages ---------------------------------------------------------------------------------------- tidyverse 1.2.1 --
## v ggplot2 2.2.1     v purrr   0.2.4
## v tibble  1.3.4     v dplyr   0.7.4
## v tidyr   0.7.2     v stringr 1.2.0
## v readr   1.1.1     v forcats 0.2.0
## -- Conflicts ------------------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
## x dplyr::select() masks MASS::select()
cor_matrix <- cor(Boston) %>% round(digits=2)
corrplot.mixed(cor_matrix, lower.col = "black", number.cex = .6)

We can see a summary of the variables in the following tables. For example for variable crime we can see the mean crime rate per capita is 3.6 and the max 88.9 which looks quite alarming. Or the mean concentration of nitrogen oxides is 0.55ppm.

summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

Finally in the following graphs we can visually see how the variables are distributed.

gather(Boston) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar()

3.2 Scaling the data

Linear Discriminant analysis makes the assumption that variables are normally distributed and the variances of each variable is the same, that is why it is better to scale the data before fitting our model.

We can see next the summaries of the scaled data. Note how the values have changed, compared to the previous summary. Now the mean for each of the variables is 0. So that indicates that all the variables have the same scale now.

After scaling, we change the object to data frame format, so we can use it later as data.

boston_scaled <- scale(Boston)
summary(boston_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
boston_scaled <- as.data.frame(boston_scaled)

3.3 Linear discriminant analysis

First we will create a categorical variable of the crime rate in the Boston dataset. For that we will use the quantiles as the break points in the categorical variable.

# First we create the quantile vector of crim:
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
# Then we create the categorical variable "crime":
crime <- cut(boston_scaled$crim, breaks = bins, inlcude.lowest = TRUE, label = c("low", "med_low", "med_high", "high"))

table(crime)
## crime
##      low  med_low med_high     high 
##      126      126      126      127

Then we will remove the old variable “crim” and add the new one “crime” to the dataset.

boston_scaled <- dplyr::select(boston_scaled, -crim)
boston_scaled <- data.frame(boston_scaled, crime)

Later, we divide the dataset to train and test sets, so that 80% of the data belongs to the train set. This will allow us to make predictions later in this chapter.

n <- nrow(boston_scaled)

# Choose randomly 80% of the rows:
ind <- sample(n, size = n*0.8)

# create the train set;
train <- boston_scaled[ind,]

# create the test set:
test <- boston_scaled[-ind,]

Now we fit the linear discriminant analysis (LDA) on the train dataset, the target variable will be crime and all the other variables as predictors.

lda.fit <- lda(crime ~., data = train)

lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2555831 0.2258065 0.2630273 0.2555831 
## 
## Group means:
##                   zn      indus         chas        nox         rm
## low       0.93790425 -0.9286343 -0.195880519 -0.8804640  0.4497423
## med_low  -0.09121565 -0.2392259 -0.012740041 -0.5800215 -0.1358458
## med_high -0.39744090  0.1288941  0.173380393  0.3389491  0.1466049
## high     -0.48724019  1.0170891 -0.004759149  1.0582308 -0.3105911
##                 age        dis        rad        tax     ptratio
## low      -0.8950042  0.8973709 -0.6875068 -0.7229791 -0.45078360
## med_low  -0.3730231  0.3668279 -0.5527736 -0.4557369  0.01597098
## med_high  0.3649601 -0.3452487 -0.3892189 -0.3183968 -0.24004509
## high      0.8142857 -0.8394101  1.6384176  1.5142626  0.78111358
##               black      lstat         medv
## low       0.3799121 -0.7692630  0.517175191
## med_low   0.2915903 -0.1254296 -0.008824296
## med_high  0.1013844 -0.0055812  0.202404287
## high     -0.7900066  0.8027613 -0.611609837
## 
## Coefficients of linear discriminants:
##                 LD1          LD2         LD3
## zn       0.09619542  0.734600214 -0.78155745
## indus   -0.01721190 -0.335453677  0.53521330
## chas    -0.06908586 -0.108523300  0.16343145
## nox      0.39775345 -0.630363942 -1.34768421
## rm      -0.08341965 -0.088632272 -0.15449242
## age      0.29774075 -0.314026058 -0.20055612
## dis     -0.07318173 -0.283142844  0.21461874
## rad      2.99582462  0.783688687 -0.13206428
## tax     -0.03479838  0.190230600  0.50501699
## ptratio  0.13361484 -0.013000027 -0.11225721
## black   -0.14136572  0.009807584  0.04017724
## lstat    0.21174387 -0.256173649  0.38435897
## medv     0.19160645 -0.390985505 -0.10668182
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9467 0.0400 0.0133

Finally we draw the LDA biplot to visualize how the data is distributed. Each class have a different colour and the arrows represent the predictor variables, whose lenght and direction are based on the coefficients and show their impact on the model.

# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2, col=classes, pch= classes)
lda.arrows(lda.fit, myscale = 1)

3.4 Predict LDA

First we will save the crime categories from the test set and then remove the crime variable from the test dataset.

# we save the correct classes from test data:
correct_classes <- test$crime

# remove the crime variable from the test data:
test <- dplyr::select(test, -crime)

Based on the trained model, the LDA model we created calculates the probability of new observations to belong in each of the classes and it classifies it to the class with the highest probability.

We predict the classes with LDA model on the test data.

lda.pred <- predict(lda.fit, newdata = test)

Finally we cross tabulate the results of our predictions using the crime categories from the test set that we saved at the beginning of this 3.4. We can observe how most of predictions are correct, only 24 of the predictions are incorrect. If we look at the probabilities, we can see how 75.4% of the predictions are correct.

table(correct = correct_classes, predicted = lda.pred$class) 
##           predicted
## correct    low med_low med_high high
##   low       15       7        1    0
##   med_low    6      18       11    0
##   med_high   0       3       17    0
##   high       0       0        0   24
table(correct = correct_classes, predicted = lda.pred$class) %>% prop.table() %>% addmargins()
##           predicted
## correct            low     med_low    med_high        high         Sum
##   low      0.147058824 0.068627451 0.009803922 0.000000000 0.225490196
##   med_low  0.058823529 0.176470588 0.107843137 0.000000000 0.343137255
##   med_high 0.000000000 0.029411765 0.166666667 0.000000000 0.196078431
##   high     0.000000000 0.000000000 0.000000000 0.235294118 0.235294118
##   Sum      0.205882353 0.274509804 0.284313725 0.235294118 1.000000000

3.5 K-means clustering

First we scale the dataset Boston.

boston_scaled2 <- scale(Boston)
summary(boston_scaled2)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
# change the object to data frame
boston_scaled2 <- as.data.frame(boston_scaled2)

We calculate the distances between the observations. We use the most common, euclidean distance.

dist_eu <- dist(boston_scaled2)

summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970

Then we run the k-means algorithm on the dataset. First we put a random number of clusters or initial cluster centers.

km <- kmeans(boston_scaled2, centers = 3)

Now we will investigate what is the optimal number of clusters. For this purpose we will first set a max number of clusters to 10. Then we will use one of the most used methods for deciding the number of cluster, sum of squares.The sum of squares or total within cluster sum of squares (TWCSS), is the sum of within cluster sum of squares (WCSS). So when you plot the number of clusters and the total WCSS, the optimal number of clusters is when the total WCSS drops radically.

# avoid the kmeans to give us every time different results
set.seed(123)

# set the maximum number of clusters to 10
k_max <- 10

# calculate the total sum of squares:
twcss <- sapply(1:k_max, function(k){kmeans (boston_scaled2, k)$tot.withinss})

# see graphically the optimal number of clusters:
qplot(x = 1:k_max, y = twcss, geom = 'line')

From the above graph we can prove how the optimal number of clusters is 2. Soo we run the k means algorithm again and visualize the results. First we see a matrix with all the variables and then zoomed for variables from 1 to 5 and from 6 to 10. On the following graphics we can observe the two clusters on the data, in red and black, and how they relate for each combination of variables

km <- kmeans(boston_scaled2, centers = 2)

pairs(boston_scaled2, col=km$cluster)

pairs(boston_scaled2[1:5], col=km$cluster)

pairs(boston_scaled2[6:10], col=km$cluster)

Bonus

First we scale the Boston dataset.

summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
boston_scaled3 <- scale(Boston)
summary(boston_scaled3)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865

Then we perform k-means.

km2 <- kmeans(boston_scaled3, center = 3)

boston_scaled3 <- as.data.frame(boston_scaled3)

Then we perform LDA using the clusters as target classes.

lda.fit2 <- lda(km2$cluster ~., data=boston_scaled3)

Visualize the results. We can observe how the most influential variables which separate the clusters are accessibility to radial highways (rad), nitrogen oxides concentration (nox) and proportion of residential land zoned for lots over 25,000 sq.ft (zn).

# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(km2$cluster)

# plot the lda results
plot(lda.fit2, dimen = 2, col=classes, pch= classes)
lda.arrows(lda.fit, myscale = 1)

Super bonus

First we run the code below for the scaled train data that we used to fit the LDA. The code creates a matrix product, which is a projection of the data points.

model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)

Then we draw a plot.

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')

Then we draw the same plot put assigning the colors to be the crime classes of the train set.

plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = train$crime)

Finally, we draw the same plot but now setting the colors to be the clusters of the k-means.

{r 3d plot3} plot_ly(x = matrix_product\(LD1, y = matrix_product\)LD2, z = matrix_product\(LD3, type= 'scatter3d', mode='markers', color = km\)cluster)

In the second graphic we can identify which observations belong to which crime classes and we can observe there is some kind of clustering within classes, especially with the class high, there is a clear cluster. The rest are not as clear.

In the last graphic we should observe the graphic where each color is a cluster, and as we could have guessed, the optimal is only 2 clusters. One for high and another one for the rest of crime classes. For some reason we could not proceed to draw this graphic.